<?php
Class Lib_Paganation
{
	const SHOW_PAGES = 7;
	public $priv_page = null;
	public $next_page = null;
	public $first_page = null;
	public $cur_page = null;
	public $page = 1;
	public $pagecount = 0;
	public $pages = array();
	public $num = 0;
	public $url_no_page_no = '';
	public $page_size = 20;
	public $is_js = false;
	
	private $query_vars;
	
	public function __construct($page = 1, $pagecount = 0, $page_size = 0, $num = 0,$is_js = false)
	{
		$this->page = $page>1?intval($page):1;
		$this->pagecount = $pagecount>0?intval($pagecount):0;
		$this->page_size = $page_size>0?intval($page_size):0;
		$this->num = $num>0?intval($num):0;
		$query_string = $_SERVER['QUERY_STRING'];
		parse_str($query_string, $this->query_vars);
		unset($this->query_vars['page']);
		$this->url_no_page_no = $this->formatUrl('','');
		$this->is_js = $is_js;
		$this->formatPaganation();
	}
	
	public function display(){
	    return "<a href></a>";
	}
	
	private function formatPaganation()
	{
		$this->cur_page['url'] = $this->is_js === false ?$this->formatUrl('page',$this->page):sprintf("javascript:%s('%d');",$this->is_js,$this->page);
		$this->cur_page['txt'] = $this->page;
		$this->priv_page['url'] =  $this->is_js === false ?$this->formatUrl('page',$this->page - 1):sprintf("javascript:%s('%d');",$this->is_js,$this->page - 1);
		$this->priv_page['txt'] = $this->page - 1;
		$this->priv_page['url'] =  $this->is_js === false ?$this->formatUrl('page',1):sprintf("javascript:%s('%d');",$this->is_js,1);
		$this->first_page['txt'] = 1;
		if($this->page < 3)
		{
			$this->first_page = null;
			if($this->page == 1)
			{
				$this->priv_page = null;
			}
		}
		$this->next_page['url'] = 
		$this->priv_page['url'] =  $this->is_js === false ?$this->formatUrl('page',$this->page + 1):sprintf("javascript:%s('%d');",$this->is_js,$this->page + 1);
		$this->next_page['txt'] = $this->page + 1;
		if($this->pagecount <= $this->page)
		{
			$this->next_page = null;
		}
		
		// 生成页号
		if($this->pagecount > 1)
		{
			$start = $this->page - floor(self::SHOW_PAGES / 2);
			if($start < 1)
			{
				$start = 1;
			}
			$end = $start + self::SHOW_PAGES - 1;
			if($end > $this->pagecount)
			{
				$end = $this->pagecount;
			}
			for($i=$start;$i<=$end;$i++)
			{
				$this->pages[] = array('page_no'=>$i,'url'=>($this->is_js === false)?$this->formatUrl('page',$i):sprintf("javascript:%s('%d');",$this->is_js,$i),'txt'=>$i);
			}
			$this->last_page['page_no'] = $this->pagecount;
			$this->last_page['url'] = ($this->is_js === false)?$this->formatUrl('page',$this->pagecount):sprintf("javascript:%s('%d');",$this->is_js,$this->pagecount);
			$this->last_page['txt'] = $this->pagecount;
		}
	}
	private function formatUrl($key, $val)
	{
		$var = $this->query_vars;
		if(!empty($key) && isset($val))
		{
			$var[$key] = $val;
		}
		return http_build_query($var);
	}
}